package com.neusoft.elmboot.service.impl;

import com.neusoft.elmboot.mapper.PointsStoreMapper;
import com.neusoft.elmboot.po.PointsRedemption;
import com.neusoft.elmboot.po.PointsStoreItem;
import com.neusoft.elmboot.service.PointsService;
import com.neusoft.elmboot.service.PointsStoreService;
import com.neusoft.elmboot.service.SuperMemberService;
import com.neusoft.elmboot.service.UserCouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PointsStoreServiceImpl implements PointsStoreService {
	
	@Autowired
	private PointsStoreMapper pointsStoreMapper;
	
	@Autowired
	private PointsService pointsService;
	
	@Autowired
	private UserCouponService userCouponService;
	
	@Autowired
	private SuperMemberService superMemberService;
	
	@Override
	public List<PointsStoreItem> getAllAvailableItems() {
		return pointsStoreMapper.getAllAvailableItems();
	}
	
	@Override
	public List<PointsStoreItem> getAllItems() {
		return pointsStoreMapper.getAllItems();
	}
	
	@Override
	public PointsStoreItem getItemById(Integer itemId) {
		return pointsStoreMapper.getItemById(itemId);
	}
	
	@Override
	@Transactional
	public boolean redeemItem(String userId, Integer itemId) {
		// 获取商品信息
		PointsStoreItem item = pointsStoreMapper.getItemById(itemId);
		if (item == null || item.getStatus() == null || item.getStatus() != 1) {
			return false; // 商品不存在或已下架
		}
		
		// 检查库存
		if (item.getStock() == null || item.getStock() <= 0) {
			return false; // 库存不足
		}
		
		// 检查用户积分
		com.neusoft.elmboot.po.User user = pointsService.getUserPointsInfo(userId);
		if (user == null) {
			return false;
		}
		
		int userPoints = user.getPoints() != null ? user.getPoints() : 0;
		int requiredPoints = item.getPointsRequired() != null ? item.getPointsRequired() : 0;
		
		if (userPoints < requiredPoints) {
			return false; // 积分不足
		}
		
		// 扣除积分（经验值不减少）
		boolean pointsDeducted = pointsService.redeemPoints(userId, requiredPoints);
		if (!pointsDeducted) {
			return false;
		}
		
		// 减少库存
		int stockUpdated = pointsStoreMapper.decreaseStock(itemId);
		if (stockUpdated <= 0) {
			throw new RuntimeException("库存更新失败");
		}
		
		// 记录兑换
		PointsRedemption redemption = PointsRedemption.builder()
			.userId(userId)
			.itemId(itemId)
			.pointsUsed(requiredPoints)
			.build();
		pointsStoreMapper.insertRedemption(redemption);
		
		// 特殊处理：会员月卡 / 会员季卡 -> 开通或续期超级会员
		if (isSuperMemberItem(item)) {
			handleSuperMemberItem(userId, item);
		} else {
			// 普通商品：按原逻辑创建优惠券（如果是优惠券类型）
			// 从商品名称中提取优惠信息来创建优惠券
			createCouponFromItem(userId, itemId, item);
		}
		
		return true;
	}
	
	/**
	 * 判断是否为超级会员相关商品（会员月卡 / 会员季卡）
	 */
	private boolean isSuperMemberItem(PointsStoreItem item) {
		if (item == null || item.getItemName() == null) {
			return false;
		}
		String name = item.getItemName();
		return name.contains("会员月卡") || name.contains("会员季卡");
	}
	
	/**
	 * 处理超级会员类商品：根据商品类型开通或续期超级会员
	 */
	private void handleSuperMemberItem(String userId, PointsStoreItem item) {
		String name = item != null ? item.getItemName() : null;
		int months = 1;
		if (name != null && name.contains("会员季卡")) {
			months = 3; // 会员季卡：三个月
		}
		boolean success = superMemberService.purchaseSuperMember(userId, months);
		if (!success) {
			// 开通失败时抛出异常，触发事务回滚，避免积分扣了但未成功开通会员
			throw new RuntimeException("开通超级会员失败");
		}
	}
	
	@Override
	public List<PointsRedemption> getRedemptionsByUserId(String userId) {
		return pointsStoreMapper.getRedemptionsByUserId(userId);
	}
	
	@Override
	public void addItem(PointsStoreItem item) {
		if (item == null || item.getItemName() == null || item.getItemName().trim().isEmpty()) {
			throw new RuntimeException("商品名称不能为空");
		}
		if (item.getPointsRequired() == null) {
			item.setPointsRequired(0);
		}
		if (item.getStock() == null) {
			item.setStock(0);
		}
		if (item.getStatus() == null) {
			item.setStatus(1);
		}
		int result = pointsStoreMapper.addItem(item);
		if (result <= 0) {
			throw new RuntimeException("新增积分商品失败");
		}
	}
	
	@Override
	public void updateItem(PointsStoreItem item) {
		if (item == null || item.getItemId() == null) {
			throw new RuntimeException("商品ID不能为空");
		}
		// 确认商品存在
		PointsStoreItem existing = pointsStoreMapper.getItemById(item.getItemId());
		if (existing == null) {
			throw new RuntimeException("商品不存在");
		}
		int result = pointsStoreMapper.updateItem(item);
		if (result <= 0) {
			throw new RuntimeException("更新积分商品失败");
		}
	}
	
	@Override
	public void updateItemStatus(Integer itemId, Integer status) {
		if (itemId == null || status == null) {
			throw new RuntimeException("商品ID或状态不能为空");
		}
		PointsStoreItem item = new PointsStoreItem();
		item.setItemId(itemId);
		item.setStatus(status);
		int result = pointsStoreMapper.updateItemStatus(item);
		if (result <= 0) {
			throw new RuntimeException("更新积分商品状态失败");
		}
	}
	
	/**
	 * 从商品信息创建优惠券
	 * 根据商品名称和描述提取优惠信息
	 */
	private void createCouponFromItem(String userId, Integer itemId, PointsStoreItem item) {
		try {
			String itemName = item.getItemName();
			String description = item.getItemDescription();
			
			System.out.println("=== 开始创建优惠券 ===");
			System.out.println("用户ID: " + userId);
			System.out.println("商品ID: " + itemId);
			System.out.println("商品名称: " + itemName);
			System.out.println("商品描述: " + description);
			
			// 从商品名称中提取优惠金额（如"10元优惠券"）
			Double discountAmount = extractDiscountAmount(itemName);
			System.out.println("提取的优惠金额: " + discountAmount);
			
			if (discountAmount == null || discountAmount <= 0) {
				System.out.println("不是优惠券类型的商品，跳过创建");
				return; // 不是优惠券类型的商品
			}
			
			// 从描述中提取最低消费金额（如"满50元可用"）
			Double minimumAmount = extractMinimumAmount(description);
			System.out.println("提取的最低消费: " + minimumAmount);
			
			// 从描述中提取有效期（默认30天）
			int validDays = extractValidDays(description);
			System.out.println("提取的有效期: " + validDays + "天");
			
			// 创建优惠券
			userCouponService.createCoupon(
				userId,
				itemId,
				itemName,
				discountAmount,
				minimumAmount,
				validDays
			);
			System.out.println("=== 优惠券创建成功 ===");
		} catch (Exception e) {
			// 记录错误但不影响兑换流程
			System.out.println("=== 优惠券创建失败 ===");
			e.printStackTrace();
		}
	}
	
	/**
	 * 从商品名称中提取优惠金额
	 */
	private Double extractDiscountAmount(String itemName) {
		if (itemName == null) {
			return null;
		}
		
		// 特殊类型商品处理
		if (itemName.contains("免配送")) {
			return 3.0; // 默认配送费3元
		}
		if (itemName.contains("会员月卡")) {
			return 10.0; // 会员月卡默认优惠10元
		}
		if (itemName.contains("会员季卡")) {
			return 30.0; // 会员季卡默认优惠30元
		}
		if (itemName.contains("新用户大礼包")) {
			return 50.0; // 新用户大礼包默认优惠50元
		}
		
		// 匹配"数字元"的模式（优先）
		java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("(\\d+)元");
		java.util.regex.Matcher matcher = pattern.matcher(itemName);
		
		if (matcher.find()) {
			try {
				return Double.parseDouble(matcher.group(1));
			} catch (NumberFormatException e) {
				return null;
			}
		}
		
		// 如果没有找到"元"，尝试匹配其他数字模式（如"10优惠券"）
		pattern = java.util.regex.Pattern.compile("(\\d+)(?:优惠|折扣|减)?");
		matcher = pattern.matcher(itemName);
		
		if (matcher.find()) {
			try {
				String numStr = matcher.group(1);
				Double amount = Double.parseDouble(numStr);
				// 如果是折扣（如99折），转换为金额
				if (itemName.contains("折")) {
					return null; // 折扣类型的不处理
				}
				return amount > 0 ? amount : null;
			} catch (NumberFormatException e) {
				return null;
			}
		}
		return null;
	}
	
	/**
	 * 从描述中提取最低消费金额
	 */
	private Double extractMinimumAmount(String description) {
		if (description == null) {
			return 0.0;
		}
		
		// 匹配"满数字元"的模式
		java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("满(\\d+)元");
		java.util.regex.Matcher matcher = pattern.matcher(description);
		
		if (matcher.find()) {
			try {
				return Double.parseDouble(matcher.group(1));
			} catch (NumberFormatException e) {
				return 0.0;
			}
		}
		return 0.0;
	}
	
	/**
	 * 从描述中提取有效期天数
	 */
	private int extractValidDays(String description) {
		if (description == null) {
			return 30; // 默认30天
		}
		
		// 匹配"数字天"的模式
		java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("(\\d+)天");
		java.util.regex.Matcher matcher = pattern.matcher(description);
		
		if (matcher.find()) {
			try {
				return Integer.parseInt(matcher.group(1));
			} catch (NumberFormatException e) {
				return 30;
			}
		}
		return 30; // 默认30天
	}
}

